<?php

namespace app\api\controller\User;

use think\Controller;
use think\Request;

class Auth extends Controller
{
    public function __construct()
	{
		parent::__construct();

		$this->UserModel = model('User.User');
	}	
	
    public function login()
    {
		
        $code = $this->request->param('code');

        $code2session = $this->code2session($code);

        $openid = isset($code2session['openid']) ? $code2session['openid'] : '';

        if(empty($openid))
        {
            $this->error('获取凭证失败');
        }

        $User = model('User.User')->where(['openid' => $openid])->find();

        if(!$User)
        {
            $this->error('您未绑定账号，请先绑定','/pages/user/bind');
        }

        $data = [
			'id' => $User['id'],
            'email' => $User['email'],
            'nickname' => $User['nickname'],
            'avatar_cdn' => $User['avatar_cdn'],
            'sex' => $User['sex'],
            'sex_text' => $User['sex_text'],
            'province' => $User['province'],
            'city' => $User['city'],
            'district' => $User['district'],
            'createtime' => $User['createtime'],
            'content' => $User['content'],
            'point' => $User['point'],
            'vip' => $User['vip'],
            'auth' => $User['auth'],
            'cover_cdn' => $User['cover_cdn'],
			'region_text' => $User['region_text'],
			'session_key' =>  $code2session['session_key']
        ];

        $this->success('登录成功',null,$data);

    }
	
	public function bind()
	{
		$code = $this->request->param('code');

		$email = $this->request->param('email');

		$password = $this->request->param('password');

		if(!$code)
		{
			$this->error('授权失败');
		}

		$code2session = $this->code2session($code);

		$openid = isset($code2session['openid']) ? $code2session['openid'] : '';

		if(empty($openid))
		{
			$this->error('获取凭证失败');
		}

		$User = model('User.User')->where(['email' => $email])->find();

		if($User)
		{
			$password = md5($password.$User['salt']);

			if($password != $User['password'])
			{
				$this->error('密码错误');
			}

			$data = [
				'id' => $User['id'],
				'openid' => $openid
			];

			$result = model('User.User')->isUpdate(true)->save($data);

			if($result === FALSE)
			{
				$this->error('绑定失败');
			}else{
				$UserData = [
					'id' => $User['id'],
					'email' => $User['email'],
					'nickname' => $User['nickname'],
					'avatar_cdn' => $User['avatar_cdn'],
					'sex' => $User['sex'],
					'sex_text' => $User['sex_text'],
					'province' => $User['province'],
					'city' => $User['city'],
					'district' => $User['district'],
					'createtime' => $User['createtime'],
					'content' => $User['content'],
					'point' => $User['point'],
					'vip' => $User['vip'],
					'auth' => $User['auth'],
					'cover_cdn' => $User['cover_cdn'],
					'region_text' => $User['region_text']
				];

				$this->success('绑定成功',null,$UserData);            
			}

		}else{
			// 密码盐
			$salt = build_ranstr();

			$password = md5($password.$salt);

			$point = model('Config')->where(['key' => 'RegisterPoint'])->value('value');


			$data = [
				'email' => $email,
				'password' => $password,
				'salt' => $salt,
				'openid' =>$openid,
				'point' => $point,
				'vip' => 1,
				'auth' => 0,
				'sex' => 0
			];

			$result = $this->UserModel->validate('common/User/User.vue')->save($data);

			if($result === FALSE)
			{
				$this->error($this->UserModel->getError());
			}else{
				$User = $this->UserModel->find($this->UserModel->id);

				$UserData = [
					'id' => $User['id'],
					'email' => $User['email'],
					'nickname' => $User['nickname'],
					'avatar_cdn' => $User['avatar_cdn'],
					'sex' => $User['sex'],
					'sex_text' => $User['sex_text'],
					'province' => $User['province'],
					'city' => $User['city'],
					'district' => $User['district'],
					'createtime' => $User['createtime'],
					'content' => $User['content'],
					'point' => $User['point'],
					'vip' => $User['vip'],
					'auth' => $User['auth'],
					'cover_cdn' => $User['cover_cdn'],
					'region_text' => $User['region_text']
				];

				$this->success('绑定成功',null,$UserData);
			}
		}
	}
	
	public function profile()
	{
		$userid = $this->request->param('userid');

		$params = $this->request->param();
		
		$user = $this->UserModel->find($userid);

		if(!$user)
		{
			$this->error('用户不存在,请重新绑定账号');
		}

		$data = [
			'id' => $userid,
			'nickname' => $params['nickname'],
			'sex' => $params['sex'],
			'content' => $params['content']
		];

		if(!empty($params['code']))
		{
			$region = model('Region')->where(['code' => $params['code']])->value('parentpath');

			if(!$region)
			{
				$this->error('所选地区不存在,请重新选择');
			}

			[$province,$city,$district] = explode(',',$region);

			$data['province'] = $province;
			$data['city'] = $city;
			$data['district'] = $district;
		}

		if(isset($_FILES['cover']) && $_FILES['cover']['size'] > 0)
		{
			$cover = upload('cover');

			if($cover['code'] == 0)
			{
				$this->error($cover['msg']);
			}

			$data['cover'] = $cover['data'];
		}

		$result = $this->UserModel->isUpdate(true)->save($data);

		if($result === FALSE)
		{
			if(!empty($data['cover']) && $_FILES['cover']['size'] > 0)
			{
				@is_file('.' . $data['cover']) && unlink('.' . $data['cover']);
			}

			$this->error('修改失败');
		}else{
			if(!empty($data['cover']) && $_FILES['cover']['size'] > 0)
			{
				@is_file('.' . $user['cover']) && unlink('.' . $user['cover']);
			}

			$User = $this->UserModel->find($userid);

			$UserData = [
				'id' => $User['id'],
				'email' => $User['email'],
				'nickname' => $User['nickname'],
				'avatar_cdn' => $User['avatar_cdn'],
				'sex' => $User['sex'],
				'sex_text' => $User['sex_text'],
				'province' => $User['province'],
				'city' => $User['city'],
				'district' => $User['district'],
				'createtime' => $User['createtime'],
				'content' => $User['content'],
				'point' => $User['point'],
				'vip' => $User['vip'],
				'auth' => $User['auth'],
				'cover_cdn' => $User['cover_cdn'],
				'region_text' => $User['region_text']
			];

			$this->success('修改成功',null,$UserData);

		}

	}

    protected function code2session($code)
    {
        // config.php => 配置一个appid和密钥
        $appid = 'wx0caf0fd76a74e2fd';
        $secret = '3672e66572aefc232b175ebd6b0ad342';

        $ApiUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";

        $result = $this->https_request($ApiUrl);

        $result = json_decode($result,true);

        if(!$result)
        {
            return false;
        }else{
            return $result;
        }
    }

    private function https_request($url,$data = null)
    {
        if(function_exists('curl_init')){
        $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
            if (!empty($data)){
                curl_setopt($curl, CURLOPT_POST, 1);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($curl);
            curl_close($curl);
            return $output;
        }else{
            return false;
        }
    }
	
	// http://www.ask.com/api/user/auth/demo
	
	
	// 获取手机号
	public function demo() {
	  $appid = isset( $_REQUEST[ 'appid' ] ) ? $_REQUEST[ 'appid' ] :'wx4f4bc4dec97d474b';
	  $sessionKey = isset( $_REQUEST[ 'sessionKey' ] ) ? $_REQUEST[ 'sessionKey' ] :'tiihtNczf5v6AKRyjwEUhQ==';
	  $encryptedData = isset( $_REQUEST[ 'encryptedData' ] ) ? $_REQUEST[ 'encryptedData' ] : "CiyLU1Aw2KjvrjMdj8YKliAjtP4gsMZM
	  QmRzooG2xrDcvSnxIMXFufNstNGTyaGS
	  9uT5geRa0W4oTOb1WT7fJlAC+oNPdbB+
	  3hVbJSRgv+4lGOETKUQz6OYStslQ142d
	  NCuabNPGBzlooOmB231qMM85d2/fV6Ch
	  evvXvQP8Hkue1poOFtnEtpyxVLW1zAo6
	  /1Xx1COxFvrc2d7UL/lmHInNlxuacJXw
	  u0fjpXfz/YqYzBIBzD6WUfTIF9GRHpOn
	  /Hz7saL8xz+W//FRAUid1OksQaQx4CMs
	  8LOddcQhULW4ucetDf96JcR3g0gfRK4P
	  C7E/r7Z6xNrXd2UIeorGj5Ef7b1pJAYB
	  6Y5anaHqZ9J6nKEBvB4DnNLIVWSgARns
	  /8wR2SiRS7MNACwTyrGvt9ts8p12PKFd
	  lqYTopNHR1Vf7XjfhQlVsAJdNiKdYmYV
	  oKlaRv85IfVunYzO0IKXsyl7JCUjCpoG
	  20f0a04COwfneQAGGwd5oa+T8yO5hzuy
	  Db/XcxxmK01EpqOyuxINew==";
	  $iv = isset( $_REQUEST[ 'iv' ] ) ? $_REQUEST[ 'iv' ] :'r7BXXKkLb8qrSNn05n0qiA==';
	  $errCode = $this->decryptData($encryptedData, $iv, $data, $appid, $sessionKey);
	  if ($errCode == 0) {
		print $data;
	  } else {
		  print($errCode . "\n");
	  }
	}
	
	public function decryptData( $encryptedData, $iv, &$data, $appid, $sessionKey) {
	  if (strlen(stripslashes($sessionKey)) != 24) {
		return -41001;
	  }
	  $aesKey=base64_decode($sessionKey);
	  if (strlen($iv) != 24) {
		return -41002;
	  }
	  $aesIV=base64_decode($iv);
	  $aesCipher=base64_decode($encryptedData);
	  $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
	  $dataObj=json_decode( $result );
	  if( $dataObj  == NULL )
	  {
		return -41003;
	  }
	  if( $dataObj->watermark->appid != $appid )
	  {
		return -41003;
	  }
	  $data = $result;
	  return 0;
	}

}
